#include "system/window.h"
#include "devices/keyboard_private.h"
#include "devices/mouse_private.h"
#include "graphics/render_private.h"
#include "graphics/sprite_private.h"

EsdlWindow window;

void esdlCreateWindow(const char* title, unsigned width, unsigned height) {
    SDL_Init(SDL_INIT_VIDEO);
    TTF_Init();

    window.width = width;
    window.height = height;

    window.fullscreen = false;

    _esdlMouseInit(&(window.mouse));
    _esdlKeyboardInit(&(window.keyboard));
    _esdlRenderInit(&(window.render));

    window.userData = NULL;

    window.screen = SDL_SetVideoMode(width, height, 32, SDL_HWSURFACE | SDL_DOUBLEBUF);
    window.sprite = _esdlCreateScreenSprite(window.screen);
    SDL_WM_SetCaption(title, NULL);
}

void esdlCloseWindow() {
    SDL_FreeSurface(window.screen);
    esdlDeleteSprite(window.sprite);

    TTF_Quit();
    SDL_Quit();
}

EsdlSprite* esdlGetScreen() {
    return window.sprite;
}

EsdlKeyboard* esdlGetKeyboard() {
    return &(window.keyboard);
}

EsdlMouse* esdlGetMouse() {
    return &(window.mouse);
}

EsdlRender* esdlGetRender() {
    return &(window.render);
}

void esdlSetWindowTitle(const char* title) {
    char* t;
    char* i;
    SDL_WM_GetCaption(&t, &i);
    SDL_WM_SetCaption(title, i);
}

void esdlGetWindowTitle(char** title) {
    char* i;
    SDL_WM_GetCaption(title, &i);
}

bool esdlSetWindowIcon(const EsdlImage* image) {
    if(image->surface->h != 32 || image->surface->w !=32) return false;
    SDL_WM_SetIcon(image->surface, NULL);
    return true;
}

void esdlSetFullScreenMode(bool fullscreen) {
    if (fullscreen) {
        window.fullscreen = true;
        window.screen = SDL_SetVideoMode(window.width, window.height, 32, SDL_HWSURFACE | SDL_DOUBLEBUF | SDL_FULLSCREEN);
    } else {
        window.fullscreen = false;
        window.screen = SDL_SetVideoMode(window.width, window.height, 32, SDL_HWSURFACE | SDL_DOUBLEBUF);
    }
}

void* esdlGetUserData() {
    return window.userData;
}

void esdlSetUserData(void* data) {
    window.userData = data;
}

void esdlTakeScreenshot(const char* path) {
    SDL_SaveBMP(window.screen, path);
}
